/**
 * Copyright 2013 Mr.Hai Mobile Developer. All rights reserved.
 * HAI PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.hector.meinewerk.model;

import java.util.ArrayList;
import java.util.Vector;

import android.graphics.Paint.Join;

import com.hector.meinewerk.common.ActionEvent;
import com.hector.meinewerk.common.ActionEventConstant;
import com.hector.meinewerk.common.ErrorConstants;
import com.hector.meinewerk.common.ModelEvent;
import com.hector.meinewerk.constants.Constants;
import com.hector.meinewerk.controller.UserController;
import com.hector.meinewerk.lib.json.me.JSONArray;
import com.hector.meinewerk.lib.json.me.JSONException;
import com.hector.meinewerk.lib.json.me.JSONObject;
import com.hector.meinewerk.lib.network.http.HTTPMessage;
import com.hector.meinewerk.lib.network.http.HTTPRequest;
import com.hector.meinewerk.lib.network.http.HTTPResponse;
import com.hector.meinewerk.lib.network.http.HttpAsyncTask;
import com.hector.meinewerk.utils.StringUtil;

/**
 * 
 * User model services
 * 
 * @author: HaiTC3
 * @version: 1.1
 * @since: 1.0 | Mar 7, 2013
 */
public class UserModel extends AbstractModelService {
	protected static UserModel instance;

	protected UserModel() {
	}

	public static UserModel getInstance() {
		if (instance == null) {
			instance = new UserModel();
		}
		return instance;
	}

	/**
	 * receive data from services success
	 */
	public void onReceiveData(HTTPMessage mes) {
		ActionEvent actionEvent = (ActionEvent) mes.getUserData();
		ModelEvent model = new ModelEvent();
		model.setParam(((HTTPResponse) mes).getRequest().getDataText());
		model.setActionEvent(actionEvent);
		// DMD check null or empty
		if (StringUtil.isNullOrEmpty((String) mes.getDataText())) {
			model.setModelCode(ErrorConstants.ERROR_COMMON);
			UserController.getInstance().handleErrorModelEvent(model);
			return;
		}
		JSONObject json;
		switch (mes.getAction()) {
		case ActionEventConstant.REQUEST_CATERGORIES_TREE:
			try {
				json = new JSONObject((String) mes.getDataText());
//				boolean status = json.getBoolean("status");
				boolean status = false;
				String strStatus = json.getString("status");
				if (strStatus.equals("1") || strStatus.equals("true")) {
					status = true;
				}
				if (status) {
					final ArrayList<Category> catergories = new ArrayList<Category>();

					try {
						JSONArray jsonCatergories = json
								.getJSONArray("categories");
						for (int i = 0; i < jsonCatergories.length(); i++) {
							JSONObject jsonCatergory = jsonCatergories
									.getJSONObject(i);
							Category category = new Category();
							category.setId(jsonCatergory.getString("id"));
							category.setName(jsonCatergory.getString("name"));
							category.setModuleName(jsonCatergory
									.getString("module_name"));
							category.setDateCreate(jsonCatergory
									.getString("date_create"));
							category.setParentId(jsonCatergory
									.getString("parent_id"));
							category.setOrder(jsonCatergory.getInt("order"));
							category.setAvatar(jsonCatergory
									.getString("avatar"));

							final ArrayList<Category> childCatergories = new ArrayList<Category>();
							JSONArray jsonChildCategories = jsonCatergory
									.getJSONArray("children");
							for (int j = 0; j < jsonChildCategories.length(); j++) {
								JSONObject jsonChildCatergory = jsonChildCategories
										.getJSONObject(j);
								Category childCategory = new Category();
								childCategory.setId(jsonChildCatergory
										.getString("id"));
								childCategory.setName(jsonChildCatergory
										.getString("name"));
								childCategory.setModuleName(jsonChildCatergory
										.getString("module_name"));
								childCategory.setDateCreate(jsonChildCatergory
										.getString("date_create"));
								childCategory.setParentId(jsonChildCatergory
										.getString("parent_id"));
								childCategory.setOrder(jsonChildCatergory
										.getInt("order"));
								childCategory.setAvatar(jsonChildCatergory
										.getString("avatar"));
								childCatergories.add(childCategory);
							}

							category.setChildCategories(childCatergories);
							catergories.add(category);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}

					model.setModelData(catergories); // success
					model.setModelCode(ErrorConstants.ERROR_CODE_SUCCESS);
					UserController.getInstance().handleModelEvent(model);
				} else {
					model.setModelCode(ErrorConstants.ERROR_DATA);
					UserController.getInstance().handleErrorModelEvent(model);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				model.setModelCode(ErrorConstants.ERROR_COMMON);
				UserController.getInstance().handleErrorModelEvent(model);
			}
			break;
		case ActionEventConstant.REQUEST_CATERGORIES:
			try {
				json = new JSONObject((String) mes.getDataText());
//				boolean status = json.getBoolean("status");
				boolean status = false;
				String strStatus = json.getString("status");
				if (strStatus.equals("1") || strStatus.equals("true")) {
					status = true;
				}
				if (status) {
					final ArrayList<Category> catergories = new ArrayList<Category>();

					try {

						JSONArray jsonCatergories = json
								.getJSONArray("categories");
						for (int i = 0; i < jsonCatergories.length(); i++) {
							JSONObject jsonCatergory = jsonCatergories
									.getJSONObject(i);
							Category category = new Category();
							category.setId(jsonCatergory.getString("id"));
							category.setName(jsonCatergory.getString("name"));
							category.setModuleName(jsonCatergory
									.getString("module_name"));
							category.setDateCreate(jsonCatergory
									.getString("date_create"));
							category.setParentId(jsonCatergory
									.getString("parent_id"));
							category.setOrder(jsonCatergory.getInt("order"));
							category.setAvatar(jsonCatergory
									.getString("avatar"));
							catergories.add(category);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

					model.setModelData(catergories); // success
					model.setModelCode(ErrorConstants.ERROR_CODE_SUCCESS);
					UserController.getInstance().handleModelEvent(model);
				} else {
					model.setModelCode(ErrorConstants.ERROR_DATA);
					UserController.getInstance().handleErrorModelEvent(model);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				model.setModelCode(ErrorConstants.ERROR_COMMON);
				UserController.getInstance().handleErrorModelEvent(model);
			}
			break;
		case ActionEventConstant.REQUEST_CATERGORY:
			try {
				json = new JSONObject((String) mes.getDataText());
//				boolean status = json.getBoolean("status");
				boolean status = false;
				String strStatus = json.getString("status");
				if (strStatus.equals("1") || strStatus.equals("true")) {
					status = true;
				}
				if (status) {
					JSONObject jsonCategory = json.getJSONObject("category");
					final Category category = new Category();
					category.setId(jsonCategory.getString("id"));
					category.setName(jsonCategory.getString("name"));
					category.setModuleName(jsonCategory
							.getString("module_name"));
					category.setDateCreate(jsonCategory
							.getString("date_create"));
					category.setParentId(jsonCategory.getString("parent_id"));
					category.setOrder(jsonCategory.getInt("order"));
					category.setAvatar(jsonCategory.getString("avatar"));

					JSONArray jsonArrayProduct = json.getJSONArray("products");
					final ArrayList<Product> products = new ArrayList<Product>();
					for (int i = 0; i < jsonArrayProduct.length(); i++) {
						JSONObject jsonProduct = jsonArrayProduct
								.getJSONObject(i);
						final Product product = new Product();
						product.setId(jsonProduct.getString("id"));
						product.setName(jsonProduct.getString("name"));
						product.setPrice(jsonProduct.getDouble("price"));
						product.setCurrency(jsonProduct.getString("currency"));
						product.setDiscount(jsonProduct.getDouble("discount"));
						product.setRemainProduct(jsonProduct
								.getString("remain_product"));
						product.setShortDesc(jsonProduct
								.getString("short_desc"));
						product.setDescription(jsonProduct
								.getString("description"));
						product.setFeatureProduct(jsonProduct
								.getInt("is_feature_product"));
						product.setSpeccial(jsonProduct.getInt("is_special"));
						product.setActive(jsonProduct.getInt("is_active"));
						product.setCreateDate(jsonProduct
								.getString("date_create"));

						// if(jsonProduct.has("tag") ||
						// !jsonProduct.isNull("tag")){
						// JSONArray jsonArrayTag =
						// jsonProduct.getJSONArray("tag");
						// final String []tags = new
						// String[jsonArrayTag.length()];
						// for(int j = 0; j < jsonArrayTag.length(); j++){
						// tags[j] =
						// jsonProduct.getJSONArray("tag").getString(j);
						// }
						// product.setImage(tags);
						// }
						//
						// if(jsonProduct.has("categories") ||
						// !jsonProduct.isNull("categories")){
						// JSONArray jsonArrayCategory =
						// jsonProduct.getJSONArray("categories");
						// final String []categories = new
						// String[jsonArrayCategory.length()];
						// for(int j = 0; j < jsonArrayCategory.length(); j++){
						// categories[j] =
						// jsonProduct.getJSONArray("categories").getString(j);
						// }
						// product.setImage(categories);
						// }
						//
						// if(jsonProduct.has("colors") ||
						// !jsonProduct.isNull("colors")){
						// JSONArray jsonArrayColor =
						// jsonProduct.getJSONArray("colors");
						// final String []colors = new
						// String[jsonArrayColor.length()];
						// for(int j = 0; j < jsonArrayColor.length(); j++){
						// colors[j] =
						// jsonProduct.getJSONArray("colors").getString(j);
						// }
						// product.setImage(colors);
						// }
						//
						// if(jsonProduct.has("sizes") ||
						// !jsonProduct.isNull("sizes")){
						// JSONArray jsonArraySize =
						// jsonProduct.getJSONArray("sizes");
						// final String []sizes = new
						// String[jsonArraySize.length()];
						// for(int j = 0; j < jsonArraySize.length(); j++){
						// sizes[j] =
						// jsonProduct.getJSONArray("sizes").getString(j);
						// }
						// product.setImage(sizes);
						// }
						//
						// if(jsonProduct.has("weights") ||
						// !jsonProduct.isNull("weights")){
						// JSONArray jsonArrayWeight =
						// jsonProduct.getJSONArray("weights");
						// final String []weights = new
						// String[jsonArrayWeight.length()];
						// for(int j = 0; j < jsonArrayWeight.length(); j++){
						// weights[j] =
						// jsonProduct.getJSONArray("weights").getString(j);
						// }
						// product.setImage(weights);
						// }

						if (jsonProduct.has("image")
								|| !jsonProduct.isNull("image")) {
							JSONArray jsonArrayImage = jsonProduct
									.getJSONArray("image");
							final String[] image = new String[jsonArrayImage
									.length()];
							for (int j = 0; j < jsonArrayImage.length(); j++) {
								image[j] = jsonProduct.getJSONArray("image")
										.getString(j);
							}
							product.setImage(image);
						}

						// if(jsonProduct.has("medias") ||
						// !jsonProduct.isNull("medias")){
						// JSONArray jsonArrayMedia =
						// jsonProduct.getJSONArray("medias");
						// final String []medias = new
						// String[jsonArrayMedia.length()];
						// for(int j = 0; j < jsonArrayMedia.length(); j++){
						// medias[j] =
						// jsonProduct.getJSONArray("medias").getString(j);
						// }
						// product.setImage(medias);
						// }

						products.add(product);
					}

					category.setProducts(products);

					model.setModelData(category); // success
					model.setModelCode(ErrorConstants.ERROR_CODE_SUCCESS);
					UserController.getInstance().handleModelEvent(model);
				} else {
					model.setModelCode(ErrorConstants.ERROR_DATA);
					UserController.getInstance().handleErrorModelEvent(model);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				model.setModelCode(ErrorConstants.ERROR_COMMON);
				UserController.getInstance().handleErrorModelEvent(model);
			}
			break;
		case ActionEventConstant.REQUEST_PRODUCT:

			try {
				json = new JSONObject((String) mes.getDataText());
//				boolean status = json.getBoolean("status");
				boolean status = false;
				String strStatus = json.getString("status");
				if (strStatus.equals("1") || strStatus.equals("true")) {
					status = true;
				}
				if (status) {
					JSONObject jsonProduct = json.getJSONObject("product");
					Product product = new Product();
					product.setId(jsonProduct.getString("id"));
					product.setName(jsonProduct.getString("name"));
					product.setPrice(jsonProduct.getDouble("price"));
					product.setCurrency(jsonProduct.getString("currency"));
					product.setDiscount(jsonProduct.getDouble("discount"));
					product.setRemainProduct(jsonProduct
							.getString("remain_product"));
					product.setShortDesc(jsonProduct.getString("short_desc"));
					product.setDescription(jsonProduct.getString("description"));
					product.setFeatureProduct(jsonProduct
							.getInt("is_feature_product"));
					product.setSpeccial(jsonProduct.getInt("is_special"));
					product.setActive(jsonProduct.getInt("is_active"));
					product.setCreateDate(jsonProduct.getString("date_create"));
					product.setTags(jsonProduct.getString("tag"));
					product.setOwnerEmail(jsonProduct.getString("owner_email"));

					// if(jsonProduct.has("tag") || !jsonProduct.isNull("tag")){
					// JSONArray jsonArrayTag = jsonProduct.getJSONArray("tag");
					// final String []tags = new String[jsonArrayTag.length()];
					// for(int j = 0; j < jsonArrayTag.length(); j++){
					// tags[j] = jsonProduct.getJSONArray("tag").getString(j);
					// }
					// product.setImage(tags);
					// }
					//
					// if(jsonProduct.has("categories") ||
					// !jsonProduct.isNull("categories")){
					// JSONArray jsonArrayCategory =
					// jsonProduct.getJSONArray("categories");
					// final String []categories = new
					// String[jsonArrayCategory.length()];
					// for(int j = 0; j < jsonArrayCategory.length(); j++){
					// categories[j] =
					// jsonProduct.getJSONArray("categories").getString(j);
					// }
					// product.setImage(categories);
					// }
					//
					// if(jsonProduct.has("colors") ||
					// !jsonProduct.isNull("colors")){
					// JSONArray jsonArrayColor =
					// jsonProduct.getJSONArray("colors");
					// final String []colors = new
					// String[jsonArrayColor.length()];
					// for(int j = 0; j < jsonArrayColor.length(); j++){
					// colors[j] =
					// jsonProduct.getJSONArray("colors").getString(j);
					// }
					// product.setImage(colors);
					// }
					//
					// if(jsonProduct.has("sizes") ||
					// !jsonProduct.isNull("sizes")){
					// JSONArray jsonArraySize =
					// jsonProduct.getJSONArray("sizes");
					// final String []sizes = new
					// String[jsonArraySize.length()];
					// for(int j = 0; j < jsonArraySize.length(); j++){
					// sizes[j] =
					// jsonProduct.getJSONArray("sizes").getString(j);
					// }
					// product.setImage(sizes);
					// }
					//
					// if(jsonProduct.has("weights") ||
					// !jsonProduct.isNull("weights")){
					// JSONArray jsonArrayWeight =
					// jsonProduct.getJSONArray("weights");
					// final String []weights = new
					// String[jsonArrayWeight.length()];
					// for(int j = 0; j < jsonArrayWeight.length(); j++){
					// weights[j] =
					// jsonProduct.getJSONArray("weights").getString(j);
					// }
					// product.setImage(weights);
					// }

					// if(jsonProduct.has("image") ||
					// !jsonProduct.isNull("image")){
					// JSONArray jsonArrayImage =
					// jsonProduct.getJSONArray("image");
					// final String []image = new
					// String[jsonArrayImage.length()];
					// for(int j = 0; j < jsonArrayImage.length(); j++){
					// image[j] =
					// jsonProduct.getJSONArray("image").getString(j);
					// }
					// product.setImage(image);
					// }

					// if(jsonProduct.has("medias") ||
					// !jsonProduct.isNull("medias")){
					// JSONArray jsonArrayMedia =
					// jsonProduct.getJSONArray("medias");
					// final String []medias = new
					// String[jsonArrayMedia.length()];
					// for(int j = 0; j < jsonArrayMedia.length(); j++){
					// medias[j] =
					// jsonProduct.getJSONArray("medias").getString(j);
					// }
					// product.setImage(medias);
					// }
					if (jsonProduct.has("medias")
							|| !jsonProduct.isNull("medias")) {
						JSONArray jsonArrayMedia = jsonProduct
								.getJSONArray("medias");
						final String[] medias = new String[jsonArrayMedia
								.length()];
						for (int j = 0, size = jsonArrayMedia.length(); j < size; j++) {
							JSONObject imageinfo = jsonArrayMedia
									.getJSONObject(j);
							medias[j] = imageinfo.getString("path");
						}
						product.setImage(medias);
					}

					model.setModelData(product); // success
					model.setModelCode(ErrorConstants.ERROR_CODE_SUCCESS);
					UserController.getInstance().handleModelEvent(model);
				} else {
					model.setModelCode(ErrorConstants.ERROR_DATA);
					UserController.getInstance().handleErrorModelEvent(model);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				model.setModelCode(ErrorConstants.ERROR_COMMON);
				UserController.getInstance().handleErrorModelEvent(model);
			}
			break;
		}
	}

	/**
	 * Receive data from services fail
	 */
	public void onReceiveError(HTTPResponse response) {
		ActionEvent actionEvent = (ActionEvent) response.getUserData();

		ModelEvent model = new ModelEvent();
		model.setParam(((HTTPResponse) response).getRequest().getDataText());
		model.setActionEvent(actionEvent);

		model.setModelCode(ErrorConstants.ERROR_NO_CONNECTION);
		model.setModelMessage(response.getErrMessage());
		UserController.getInstance().handleErrorModelEvent(model);

	}

	/**
	 * 
	 * request login
	 * 
	 * @param @param actionEvent
	 * @param @return
	 * @return: HTTPRequest
	 * @author: HaiTC3
	 * @date: Mar 8, 2013
	 */
	public HTTPRequest requestCatergoriesHTTP(ActionEvent actionEvent) {
		HTTPRequest re = null;
		try {
			ArrayList<String> info = (ArrayList<String>) actionEvent.userData;
			re = sendHttpRequest("categories/", Constants.HTTPCONNECTION_GET,
					info, actionEvent, HttpAsyncTask.TIME_OUT_REQUEST);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return re;
	}

	public HTTPRequest requestCatergoryHTTP(ActionEvent actionEvent) {
		HTTPRequest re = null;
		try {
			ArrayList<String> info = (ArrayList<String>) actionEvent.userData;
			re = sendHttpRequest("category/", Constants.HTTPCONNECTION_GET,
					info, actionEvent, HttpAsyncTask.TIME_OUT_REQUEST);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return re;
	}

	public HTTPRequest requestProductHTTP(ActionEvent actionEvent) {
		HTTPRequest re = null;
		try {
			ArrayList<String> info = (ArrayList<String>) actionEvent.userData;
			re = sendHttpRequest("product/", Constants.HTTPCONNECTION_GET,
					info, actionEvent, HttpAsyncTask.TIME_OUT_REQUEST);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return re;
	}

	public HTTPRequest requestCatergoriesTreeHTTP(ActionEvent actionEvent) {
		HTTPRequest re = null;
		try {
			ArrayList<String> info = (ArrayList<String>) actionEvent.userData;
			re = sendHttpRequest("categories_tree/",
					Constants.HTTPCONNECTION_GET, info, actionEvent,
					HttpAsyncTask.TIME_OUT_REQUEST);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return re;
	}
}
